package com.meeting.meetingroom_api.controller;

import com.meeting.meetingroom_api.dto.*;
import com.meeting.meetingroom_api.enums.RoomStatus;
import com.meeting.meetingroom_api.security.UserDetailsImpl;
import com.meeting.meetingroom_api.service.MeetingRoomService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/meeting-rooms")
public class MeetingRoomController {

    private final MeetingRoomService meetingRoomService;

    @Autowired
    public MeetingRoomController(MeetingRoomService meetingRoomService) {
        this.meetingRoomService = meetingRoomService;
    }

    /**
     * 管理员新增会议室
     */
    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping
    public ResponseEntity<MeetingRoomDto> createMeetingRoom(@Valid @RequestBody MeetingRoomCreateDto createDto) {
        MeetingRoomDto newRoom = meetingRoomService.createMeetingRoom(createDto);
        return new ResponseEntity<>(newRoom, HttpStatus.CREATED);
    }

    /**
     * 获取指定id和对应时间段的会议室全部信息
     */
    @GetMapping("/{roomId}")
    public ResponseEntity<MeetingRoomDto> getMeetingRoomById(
            MeetingRoomQueryDto queryDto,
            @PathVariable Integer roomId) {
        //System.out.println("开始时间："+queryDto.getDesiredStartTime()+" 结束时间："+queryDto.getDesiredEndTime());
        MeetingRoomDto room = meetingRoomService.getMeetingRoomByIdAndPeriod(roomId,queryDto);
        return ResponseEntity.ok(room);
    }

    @GetMapping("/name/{name}")
    public ResponseEntity<MeetingRoomDto> getMeetingRoomByName(@PathVariable String name) {
        MeetingRoomDto room = meetingRoomService.getMeetingRoomByName(name);
        return ResponseEntity.ok(room);
    }

    /**
     * 分页查询所有的会议室（包含各种状态的会议室）
     */
    @GetMapping
    public ResponseEntity<Page<MeetingRoomDto>> findMeetingRooms(
            MeetingRoomQueryDto queryDto,
            @PageableDefault(size = 10, sort = "roomId") Pageable pageable) {
        Page<MeetingRoomDto> roomsPage = meetingRoomService.findMeetingRooms(queryDto, pageable);
        return ResponseEntity.ok(roomsPage);
    }

    //只有空闲和维修的会议室可以被修改，不可以修改状态（前端不能传）
    @PreAuthorize("hasRole('ADMIN')")
    @PutMapping("/{roomId}")
    public ResponseEntity<MeetingRoomDto> updateMeetingRoom(
            @PathVariable Integer roomId,
            @Valid @RequestBody MeetingRoomUpdateDto updateDto) {
        MeetingRoomDto updatedRoom = meetingRoomService.updateMeetingRoom(roomId, updateDto);
        return ResponseEntity.ok(updatedRoom);
    }

    /**
     * 更新会议室状态，旧版接口（建议使用 changeRoomStatus）
     * 只允许设置 available 和 maintenance 状态
     */
    @PreAuthorize("hasAnyRole('ADMIN', 'EMPLOYEE')")
    @PatchMapping("/{roomId}/status")
    public ResponseEntity<MeetingRoomDto> updateMeetingRoomStatus(
            @PathVariable Integer roomId,
            @RequestParam RoomStatus status) {
        MeetingRoomDto updatedRoom = meetingRoomService.updateMeetingRoomStatus(roomId, status);
        return ResponseEntity.ok(updatedRoom);
    }

    /**
     * 软删除会议室（空闲或维修中的会议室）
     */
    @PreAuthorize("hasRole('ADMIN')")
    @DeleteMapping("/{roomId}")
    public ResponseEntity<Void> deleteMeetingRoom(@PathVariable Integer roomId) {
        meetingRoomService.deleteMeetingRoom(roomId);
        return ResponseEntity.noContent().build();
    }

    /**
     * 管理员专用：带操作人记录的软删除
     */
    @PreAuthorize("hasRole('ADMIN')")
    @DeleteMapping("/{roomId}/admin")
    public ResponseEntity<Void> deleteMeetingRoomWithAdmin(
            @PathVariable Integer roomId,
            @AuthenticationPrincipal UserDetailsImpl currentUser) {
        meetingRoomService.deleteMeetingRoom(roomId, currentUser.getId());
        return ResponseEntity.noContent().build();
    }

    /**
     * 管理员专用：查看已删除的会议室
     */
    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/deleted")
    public ResponseEntity<Page<MeetingRoomDto>> getDeletedMeetingRooms(
            @PageableDefault(size = 10, sort = "deletedAt", direction = Sort.Direction.DESC) Pageable pageable) {
        Page<MeetingRoomDto> deletedRooms = meetingRoomService.getDeletedMeetingRooms(pageable);
        return ResponseEntity.ok(deletedRooms);
    }

    /**
     * 管理员专用：恢复已删除的会议室
     */
    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/{roomId}/restore")
    public ResponseEntity<MeetingRoomDto> restoreMeetingRoom(
            @PathVariable Integer roomId,
            @AuthenticationPrincipal UserDetailsImpl currentUser) {
        MeetingRoomDto restoredRoom = meetingRoomService.restoreMeetingRoom(roomId, currentUser.getId());
        return ResponseEntity.ok(restoredRoom);
    }

    //已测试

    /**
     * 客户根据需求搜索会议室
     */
    @GetMapping("/recommend")
    public ResponseEntity<Page<MeetingRoomDto>> recommendMeetingRooms(
            @Valid MeetingRoomRecommendationDto recommendationDto,
            @PageableDefault(size = 10, sort = "pricePerHour", direction = Sort.Direction.ASC) Pageable pageable) {
        Page<MeetingRoomDto> recommendedRooms = meetingRoomService.recommendMeetingRooms(recommendationDto, pageable);
        return ResponseEntity.ok(recommendedRooms);
    }


    @PreAuthorize("hasAnyRole('ADMIN', 'EMPLOYEE')")
    @GetMapping("/status-overview")//已测试，用于查看所有会议室的状态
    public ResponseEntity<List<MeetingRoomDto>> getRoomStatusOverview() {
        List<MeetingRoomDto> rooms = meetingRoomService.getAllMeetingRooms();
        return ResponseEntity.ok(rooms);
    }

    /**
     * 根据不同会议室状态查询对应会议室
     */
    @PreAuthorize("hasAnyRole('ADMIN', 'EMPLOYEE')")
    @GetMapping("/status/{status}")
    public ResponseEntity<List<MeetingRoomDto>> getRoomsByStatus(@PathVariable RoomStatus status) {
        List<MeetingRoomDto> rooms = meetingRoomService.getRoomsByStatus(status);
        return ResponseEntity.ok(rooms);
    }

    /**
     *员工对会议室状态及其对应订单状态的相应修改
     */
    @PreAuthorize("hasAnyRole('EMPLOYEE', 'ADMIN')")
    @PutMapping("/changeRoomStatus")
    public ResponseEntity<MeetingRoomDto> changeRoomStatus(@Valid @RequestBody RoomStatusChangeDto roomStatusChangeDto,
                                                           @AuthenticationPrincipal UserDetailsImpl currentUser) {
        MeetingRoomDto rooms = meetingRoomService.changeRoomStatus(roomStatusChangeDto.getRoomId(),
                roomStatusChangeDto.getStatus(), roomStatusChangeDto.getRoomConditionNotes(),currentUser.getId());
        return ResponseEntity.ok(rooms);
    }

}